#include "tools.h"

bool readIntFromSD(File file, int &intVar) {
  if (file.available()) {
    String line = "";
    char ch;
    while (file.available()) {
      ch = file.read();
      if (ch == ' ' || ch == '\n') break;
      line += ch;
    }
    intVar = line.toInt();
    return true;
  }
  return false;
}

bool readDoubleFromSD(File file, double &doubleVar) {
  if (file.available()) {
    String line = "";
    char ch;
    while (file.available()) {
      ch = file.read();
      if (ch == ' ' || ch == '\n') break;
      line += ch;
    }
    doubleVar = line.toDouble();
    return true;
  }
  return false;
}

bool readWordFromSD(File file, int maxLength, char *cmd) {
  if (file.available()) {
    int index = 0;
    while (file.available() && index < maxLength - 1) {
      char ch = file.read();
      if (index == 0 && (ch == ' ' || ch == '\r' || ch == '\n')) {
        continue;
      }
      if (ch == ' ' || ch == '\n' || ch == '\r') {
        // 如果到达行尾，停止读取
        break;
      }
      cmd[index++] = ch;
    }
    cmd[index] = '\0'; // 确保字符串以空字符结尾
    return true;
  }
  return false;
}

bool readLineFromSD(File file, int maxLength, char *cmd) {
  if (file.available()) {
    int index = 0;
    while (file.available() && index < maxLength - 1) {
      char ch = file.read();
      if (ch == '\n') {
        // 如果到达行尾，停止读取
        cmd[index++] = '\n';
        break;
      }
      cmd[index++] = ch;
    }
    cmd[index] = '\0'; // 确保字符串以空字符结尾
    return true;
  }
  return false;
}